﻿var cmsLoadingHTML = '<img src="/CMS/File/Resource?Assembly=OpenQuarters.WebQuarters.Core.Web&filename=Areas.CMS.Content.Images.icon_loading.gif" class="cmsIcon" alt=" " /> Loading...';

jQuery.fn.cmsPageInfo = function(opts) {
    var opts = jQuery.extend({}, opts || {});
    return this.each(function(i, e) {
        var element = $(e);
        element.show(0).modal();
        element.jForm({
            form: '/CMS/File/Resource?Assembly=OpenQuarters.WebQuarters.Core.Web&filename=Areas.CMS.Content.Forms.CMSPageInfo.tpl',
            object: cmsPageVersion,
            onProceed: function(o) {
                cmsPageVersion = $.extend(cmsPageVersion, o);
                cmsSaveDraft(function(r) {
                    if (r.success) {
                        window.location = self.location;
                    }
                });
            },
            onCancel: function() {
                $.modal.close();
            }
        });
    });
};

jQuery.fn.cmsPageManager = function(opts) {
    var opts = jQuery.extend({}, opts || {});
    return this.each(function(i, e) {
        var element = $(e);
        element.show(0).modal();
        element.html(cmsLoadingHTML).setTemplateURL('/CMS/File/Resource?Assembly=OpenQuarters.WebQuarters.Core.Web&filename=Areas.CMS.Content.Templates.CMSPageManager.tpl');
        $.postJSON("/cms/pages/get", {}, function(pages) {

        $.postJSON("/cms/pages/getTemplates", {}, function(templates) {
                element.setParam('templates', templates || {})
                    .processTemplate(pages);

                element.find('ul.cmsPageManager li:first ul:first').toggle();
                element.find('ul.cmsPageManager li ul li ul').hide(0);

                element.find('ul.cmsPageManager li a span').each(function() {
                    $(this).click(function() {
                        var parentUL = $(this).parent().parent().find('ul');
                        parentUL.toggle();
                        $(this).parent().blur();
                    });
                });
                element.find('ul.cmsPageManager li a').hover(function() {
                    $(this).addClass('hover');
                    $(this).find('.opts').remove();
                    $.cmsPageManagerOptions(this);

                }, function() {
                    $(this).removeClass('hover');
                    $(this).find('.opts').remove();
                }).click(function() { return false; });

                $('#cmsPageManagerPageTitle').keyup(function(event) {
                    if (event.keyCode == 27) {
                        $('#cmsPageManagerAddPageWrapper').hide(0);
                        return false;
                    }
                });

                $('#cmsPageManagerAddCancelBtn').click(function() {
                    $('#cmsPageManagerAddPageWrapper').hide(0);
                    return false;
                });

                $('#cmsPageManagerAddPageWrapper form').submit(function() {
                    $(this).submit(function() { return false; });
                    $('#cmsPageManagerAddPageWrapper .cmsBtn').attr('disabled', 'disabled');
                    $.postJSON('/cms/pages/add', { parentId: $('#cmsPageManagerPageParent').val(), title: $('#cmsPageManagerPageTitle').val(), template: $('#cmsPageManagerPageTemplate').val() }, function(json) {
                        element.cmsPageManager({});
                    });
                    return false;
                });

                element.find('ul.cmsPageManager ul').sortable({ containment: 'parent', cursor: 'crosshair', update: function(event, ui) {
                    var pageOrdering = [];
                    $(ui.item).parent().find(' > li').each(function() {
                        pageOrdering.push($($(this).find('a:first')[0]).attr('rel'));
                    });
                    var parentId = $($(ui.item).parent().parent().find('a:first')[0]).attr('rel');
                    $.postJSON('/cms/pages/SetOrder', { parent: parentId, ordering: $.compactJSON(pageOrdering) }, function(json) {
                        if (json.success) {
                            // TODO: Inform user of workflow item in Inbox
                        }
                    });
                }
                });
            });
        });
    });
};

$.cmsPageManagerOptions = function(anchor) {
    var thisOpts = $('<div class="opts"></div>');
    var thisPageId = $(anchor).attr('rel');
    var thisPageTitle = $(anchor).attr('title');

    var addLink = $('<img src="/CMS/File/Resource?Assembly=OpenQuarters.WebQuarters.Core.Web&filename=Areas.CMS.Content.Images.sicon_plus.png" rel="' + thisPageId + '" class="cmsPageSelectorAddPageLink tooltip" title="Add a new page, as a child of \'' + thisPageTitle + '\'" />');
    var deleteLink = $('<img src="/CMS/File/Resource?Assembly=OpenQuarters.WebQuarters.Core.Web&filename=Areas.CMS.Content.Images.sicon_delete.png" rel="' + thisPageId + '" class="cmsPageSelectorDeletePageLink tooltip" title="Submit page \'' + thisPageTitle + '\' for deletion" />');
    var goLink = $('<img src="/CMS/File/Resource?Assembly=OpenQuarters.WebQuarters.Core.Web&filename=Areas.CMS.Content.Images.sicon_go.png" rel="' + $(anchor).attr('href') + '" class="cmsPageSelectorGoLink tooltip" title="Go to page \'' + thisPageTitle + '\'" />');

    addLink.click(function() {
        $('#cmsPageManagerMessage').hide();
        $('#cmsPageManagerPageParent').val($(this).attr('rel'));
        $('#cmsPageManagerAddPageWrapper').show(0);
        $('#cmsPageManagerPageTitle').focus().select();
    });

    deleteLink.click(function() {
        $.postJSON('/cms/pages/Delete', { id: $(this).attr('rel') }, function(json) {
            if (json.success) {
                $('#cmsPageManagerMessage').show(0).find('.cmsInfo').text('The selected page has been flagged for deletion - deletion of pages must be approved by an administrator');
            }
        });
    });

    goLink.click(function() {
        window.location = $(this).attr('rel');
    });

    thisOpts.append(addLink);
    thisOpts.append(deleteLink);
    thisOpts.append(goLink);
    $(anchor).append(thisOpts).tooltip();
};


jQuery.fn.cmsPageVersionManager = function(opts) {
    var opts = jQuery.extend({}, opts || {});
    return this.each(function(i, e) {
        var element = $(e);
        element.modal();
        element.html(cmsLoadingHTML).setTemplateURL('/CMS/File/Resource?Assembly=OpenQuarters.WebQuarters.Core.Web&filename=Areas.CMS.Content.Templates.CMSPageVersionManager.tpl');
        $.postJSON("/cms/pages/GetPageVersions/" + cmsPageVersion.json_PageId, {}, function(pages) {
            element.processTemplate(pages);
            element.find('li:first').css('color', '#000').css('background', '#e3ffe3');
            element.find('li a').css('cursor', 'pointer');
            element.find('li a.live').click(function() {
                $.postJSON('/cms/pages/makeLive/' + cmsPageVersion.json_PageId, { version: $(this).attr('rel') }, function(response) {
                    cmsPageVersionCheck();
                });
                return false;
            });
            element.find('li a.draft').click(function() {
                $.postJSON('/cms/pages/copyDraft/' + cmsPageVersion.json_PageId, { version: $(this).attr('rel') }, function(response) {
                    cmsPageVersionCheck();
                });
                return false;
            });

            $('#cmsPageVersionManagerContainer').keyup(function(event) {
                if (event.keyCode == 27) {
                    $('#cmsPageVersionManagerContainer').hide(0);
                    return false;
                }
            });
        });
    });
};



jQuery.fn.cmsInbox = function(opts) {
    var opts = jQuery.extend({}, opts || {
        open: null
    });
    return this.each(function(i, e) {
        var element = $(e);
        element.setTemplateURL('/CMS/File/Resource?Assembly=OpenQuarters.WebQuarters.Core.Web&filename=Areas.CMS.Content.Templates.CMSInbox.tpl');
        $.postJSON("/cms/account/GetMessages", {}, function(msgs) {
            element.processTemplate(msgs);

            element.find('li').click(function() {
                cmsInboxOpenMessage(this, element, msgs);
            });

            if (opts.open) {
                var openLI = $.grep(element.find('li'), function(i) { return $(i).attr('rel') == opts.open; })[0];
                if (openLI) {
                    cmsInboxOpenMessage(openLI, element, msgs);
                }
            }
        });
    });

    function cmsInboxOpenMessage(li, inbox, msgs) {
        var msgId = $(li).attr('rel');
        var msg = $.grep(msgs, function(i) { return i.json_MessageId == msgId; })[0];

        $('#cmsInboxMessage').html('<h2>' + msg.json_Subject + '</h2>' + (msg.json_Body ? '<p>' + msg.json_Body + '</p>' : ''));

        if (msg.json_WorkflowItem) {
            var workflow = $('<div id="workflow_' + msg.json_WorkflowItem.json_WorkflowItemId + '"></div>');
            $('#cmsInboxMessage').append(workflow);
            workflow.cmsWorkflowItem({ messageId: msg.json_MessageId, workflowItem: msg.json_WorkflowItem, inbox: inbox });
        }

        if (!msg.json_Read) {
            $.postJSON('/cms/account/MarkMessageAsRead/' + msg.json_MessageId, {}, function() {
                $(li).addClass('cmsRead');
            });
        }
    }
};

jQuery.fn.cmsWorkflowItem = function(opts) {
    var opts = jQuery.extend({}, opts || {
        messageId: null,
        workflowItem: null,
        inbox: null
    });
    return this.each(function(i, e) {
        var element = $(e);
        if (cmsIsAuthenticated) {
            element.setTemplateURL('/CMS/File/Resource?Assembly=OpenQuarters.WebQuarters.Core.Web&filename=Areas.CMS.Content.Templates.WorkflowItem.tpl');
            if (opts.workflowItem) {
                element.processTemplate(opts.workflowItem);

                element.find('.cmsApproveWorkflowItem').click(function() {
                    $.postJSON('/cms/admin/ApproveWorkflow/' + opts.workflowItem.json_WorkflowItemId, {}, function(r) {
                        $(opts.inbox).cmsInbox({ open: opts.messageId });
                    });
                    return false;
                });

                element.find('.cmsRejectWorkflowItem').click(function() {
                    $.postJSON('/cms/admin/RejectWorkflow/' + opts.workflowItem.json_WorkflowItemId, {}, function(r) {
                        $(opts.inbox).cmsInbox({ open: opts.messageId });
                    });
                    return false;
                });

                element.find('.addCommentBtn').click(function() {
                    var wfId = $(this).attr('rel');
                    var comment = element.find('#txtComment_' + wfId).val();
                    $.postJSON('/cms/admin/AddWorkflowComment', { id: wfId, comment: comment }, function(r) {
                        if (r.success) {
                            $(opts.inbox).cmsInbox({ open: opts.messageId });
                        }
                    });
                    return false;
                });
            }
        }
    });
};

jQuery.fn.tooltip = function(opts) {
    var xOffset = 10;
    var yOffset = 20;
    $(this).each(function() {
        $(this).find('.tooltip').hover(function(e) {
            this.t = $(this).attr('title');
            $(this).attr('title', '');
            $("body").append("<p id='cmsTooltip'>" + this.t + "</p>");
            $("#cmsTooltip")
			.css("top", (e.pageY - xOffset) + "px")
			.css("left", (e.pageX + yOffset) + "px")
			.fadeIn("fast");
        },
	function() {
	    $(this).attr('title', this.t);
	    $("#cmsTooltip").remove();
	}).mousemove(function(e) {
	    $("#cmsTooltip")
			.css("top", (e.pageY - xOffset) + "px")
			.css("left", (e.pageX + yOffset) + "px");
	});
    });
};

function cmsEditorUpdateInbox(category) {
    cmsEditorUpdateInboxSingle(category);
    window.setTimeout('cmsEditorUpdateInbox(\'' + category + '\')', 30000);
}

function cmsEditorUpdateInboxSingle(category) {
    $.post("/cms/account/GetMessageCount/" + category, {}, function(count) {
        $('.cmsInboxCount').html(count).parent().css('font-weight', count == '0' ? 'normal' : 'bold');
    });
}
